import axios, { AxiosError, AxiosInstance, AxiosResponse, CreateAxiosDefaults, InternalAxiosRequestConfig } from "axios";


//封装axios 类封装
class Ajax{
    //请求实例
   private instance:AxiosInstance   //AxiosInstance约束实例
    constructor(config:CreateAxiosDefaults){
        this.instance=axios.create(config)
        //实例化之后调用拦截方法
        this.beforeRequest()
        this.beforeResponse()
    }
    //拦截
private beforeRequest(){   //请求拦截
this.instance.interceptors.request.use((req:InternalAxiosRequestConfig)=>{
// req.headers.Authorization
    return req
},(err:AxiosError)=>{
    //拦截错误
    console.log(err,123);
    return err
    
})
}
private beforeResponse(){  //响应拦截
    this.instance.interceptors.response.use((res:AxiosResponse)=>{
        return res
    })
}
//请求方法
post<T>(url:string,data?:T):Promise<AxiosResponse>{   //promise后台返回的数据
    return this.instance({
        method:"post",
        data,
        url,
    })
}
get<T>(url:string,params?:T):Promise<AxiosResponse>{   //promise后台返回的数据
    return this.instance({
        method:"get",
        params,  //拼装在路径后面url?键=值&键=值
        url,
    })
}
}
export default Ajax